package com.boe.csb.core.common.utils;

import java.util.Random;

import javax.servlet.http.HttpSession;

/**
 * 生成验证码
 * date 2016年11月29日
 * @author xc
 */
public class VerifyCodeUtils {
	
	public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";

	public static final String NUM_VERIFY_CODES = "0123456789";
	
	private static Random random = new Random();
	
	public static String generateVerifyCode(){
		return generateVerifyCode(4);
	}

	/**
	 * 生成数字校验码
	 * @return
	 */
	public static String generateNumVerifyCode(){
		return generateVerifyCode(4, NUM_VERIFY_CODES);
	}
	
	public static String generateVerifyCode(int verifySize){
		return generateVerifyCode(verifySize, VERIFY_CODES);
	}
	
	public static String generateVerifyCode(int verifySize, String sources){
		
		if(sources == null || sources.length() == 0){
			sources = VERIFY_CODES;
		}
		
		int codesLen = sources.length();
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<verifySize; i++){
			sb.append(sources.charAt(random.nextInt(codesLen)));
		}
		
		return sb.toString();
	}
	
	/**
	 * 获取session里面缓存的验证码
	 * @param httpSession
	 * @param key
	 * @param clear
	 * @return
	 */
	public static String getCacheVerifyCode(HttpSession httpSession, String key, boolean clear){
		
		String cacheVerifyCode = (String) httpSession.getAttribute(key);
		if(clear){
			httpSession.removeAttribute(key);
		}
		
		return cacheVerifyCode;
	}
}
